package com.yt.contorlller;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

@RestController
@Slf4j
public class MqController {
    @GetMapping("/mq/in")
    public String in() {
        ConnectionFactory factory=new ConnectionFactory();
        factory.setHost("192.168.109.101");
        factory.setUsername("yangtao");
        factory.setPassword("123456");
        try {
            Connection con=factory.newConnection();
            Channel channel=con.createChannel();
            channel.queueDeclare("mq",false ,false,false,null);
            channel.basicPublish("","mq",null,"这是一个消息".getBytes(StandardCharsets.UTF_8));
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
        return "in";
    }

    @GetMapping("/mq/out")
    public String out() {
        ConnectionFactory factory=new ConnectionFactory();
        factory.setHost("192.168.109.101");
        factory.setUsername("yangtao");
        factory.setPassword("123456");
        try {
            Connection con=factory.newConnection();
            Channel channel=con.createChannel();
            channel.queueDeclare("mq",false ,false,false,null);
            //channel.basicPublish("","mq",null,"这是一个消息".getBytes(StandardCharsets.UTF_8));
            channel.basicConsume("mq",true,(a,b)->{
                log.info(a);
                log.info(new String(b.getBody(),"utf8"));
            },a->{
             log.info(a);
            });
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
        return "out";
    }
}
